<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Authorization;
use App\Models\Carousel;
use App\Models\Category;
use App\Models\Product;
use App\Models\ProductCoupon;
use App\Models\ProductCouponCode;
use App\Jobs\SendRegisterEmail;
use App\Transformers\UserTransformer;
use App\Models\UserCoupon;
use App\Models\Coupon;
use Illuminate\Support\Facades\Redis;
use Elasticsearch\ClientBuilder;
use Log;

class ProductController extends BaseController
{
    public function carousels(Request $request)
    {
        $carousels = Carousel::where('is_active', '=', '1')->get();
        foreach ($carousels as &$carousel) {
            $carousel->pic_url = $this->imageBaseUrl . $carousel->pic_url;
        }
        return $this->returnSuccess($carousels);
    }
    
    public function categories(Request $request)
    {
        $categories = Category::where('is_active', '=', '1')->get();
        foreach ($categories as $category) {
            if ($category->pic) {
                $category->pic = $this->imageBaseUrl . $category->pic;
            }
        }
		$catArr = [];
		$kvArr = [];
		foreach($categories as $cat){
			if($cat['pic'] == ''){
				$cat['pic'] = 'http://dummyimage.com/100x100';
			}
			$catArr[$cat['pid']][] = $cat;
			$kvArr[$cat['id']] = $cat;
		}
		$retArr = [];
		$list = [];
		foreach($catArr as $pid => $cats){
			if($pid == 0){
				foreach($cats as $cat){
					$id = $cat['id'];
					if(!isset($catArr[$id])){
						continue;
					}
					$list[] = [
						'id' => $kvArr[$id]['id'],
						'zh_name' => $kvArr[$id]['zh_name'],
						'en_name' => $kvArr[$id]['en_name'],
						'pic' => $kvArr[$id]['pic'],
						'content' => $catArr[$id],
					];
				}
			}
		}
		$retArr['list'] = $list;
		//头部banner , @todo
		$retArr['banner'] = [
			[
				"src" => "http://dummyimage.com/530x180",
			],
			[
				"src" => "http://dummyimage.com/530x180",
			],
		];
        return $this->returnSuccess($retArr);
    }
    
    /**
     *
     * 获取产品列表
     * @param {Object} Request
     */
    public function index(Request $request)
    {
        //$longitude = $request->headers['longitude'];
        $longitude = $request->get('longitude');
		$latitude  = $request->get('latitude');
		$page      = $request->get('page');
		$size      = $request->get('size');
		$keyword   = $request->get('keyword');
		$begin     = ($page - 1) * $size;
        $queryNum  = $begin + $size;
		
		$hosts    = array(env('ELASICSEARCHHOST'));
		$client   = ClientBuilder::create()->setHosts($hosts)->build();
		//批量搜索
		//https://www.elastic.co/guide/cn/elasticsearch/guide/current/combining-filters.html
		$must     = [
					'match' => [ // 搜索条件
						'name' => $keyword
					]
				];
		//地理距离过滤器（ geo_distance ）以给定位置为圆心画一个圆，来找出那些地理坐标落在其中的文档
		//https://www.elastic.co/guide/cn/elasticsearch/guide/current/geo-distance.html
		$query    = [
			'bool' => [ //bool 是一个复合的过滤器，可以接受多个子过滤器
				'filter' => [
					"geo_distance" => [
						"distance" => "10000km",
						"location" => [
							"lat" => $latitude,
							"lon" => $longitude
						]
					]
				]
			]
		];
		//AND 关系 
		if ($keyword) {
			$query['bool']['must'] = $must; // 搜索条件
		}
		$sort = [
			"_geo_distance" => [
				"location" => [
					"lat" => $latitude,
					"lon" => $longitude
				],
				"order" => "asc",
				"unit" => "km"
			]
		];
		$params   = [
			'index' => 'cut_shop',  //['my_index1', 'my_index2'],可以通过这种形式进行跨库查询
			'type'  => '_doc', //['my_type1', 'my_type2'],
			'body'  => [
				// 'from'  => $begin, // 分页  这里全部找出
				// 'size'  => $size, // 每页数量
				'query' => $query,
				'sort'  => $sort // 排序
			]
  		]; 
		//return $this->returnSuccess($params);
		$response = $client->search($params);
		$shop_ids = [];
		$shopHits = $response['hits']['hits'];
	   foreach ($shopHits as $item) {
	   	\array_push($shop_ids, $item['_id']);
	   }
	   
	   //获取商品
	   $query    = [
	   	'bool' => [ //bool 是一个复合的过滤器，可以接受多个子过滤器
	   		'filter' => [
	   			"geo_distance" => [
	   				"distance" => "10000km",
	   				"location" => [
	   					"lat" => $latitude,
	   					"lon" => $longitude
	   				]
	   			]
	   		]
	   	]
	   ];
	   //AND 关系 
	   if ($keyword) {
			$query['bool']['must'] = [
					'match' => [
						'title' => $keyword
					]
				];
	   }
	   $sort = [
			"_geo_distance" => [
				"location" => [
					"lat" => $latitude,
					"lon" => $longitude
				],
				"order" => "asc",
				"unit" => "km"
			]
	   ];
	   $params   = [
			'index' => 'cut_product',
			'type'  => '_doc',
			'body'  => [
				'query' => $query,
				'sort'  => $sort // 排序
			]
	   ];
	   $response = $client->search($params);
	   $productHits = $response['hits']['hits'];
	   $product_ids = [];
	   foreach ($productHits as $item) {
			\array_push($product_ids, $item['_id']);
	   }
	   
	   if(!empty($shop_ids)){
			$products2 = Product::whereIn('shop_id', $shop_ids)->with('shop')->get();
			foreach($products2 as $product){
				if($product['id'] && !in_array($product['id'], $product_ids)){
					$product_ids[] = $product['id'];
				}
			}
	   }
	   $products = Product::whereIn('id', $product_ids)->with('shop')->get();
		
        foreach ($products as $k => $product) {
			if ($k < $begin || $k >= ($begin + $size)) {
			    unset($products[$k]);
				continue;
			}   
            $pics = $product->pics;
            foreach ($pics as $key => $pic) {
                $new_pic = env('CUT_IMAGE_UTL') . $pic;
                $pics[$key] = $new_pic;
            }
            $products[$k]['pics'] = $pics;
			foreach ($shopHits as $shop) {
				if ($shop['_id'] == $product->shop_id) {
					$distance = round($shop['sort'][0]).'km';
					if($shop['sort'][0] < 1){
						$distance = round($shop['sort'][0]*1000).'m';
					}
					$products[$k]['distance'] = $distance;
				}
			}
			if($product->view_pic){
				$products[$k]['view_pic'] = env('CUT_IMAGE_UTL') .$product->view_pic;
			}
        }
        return $this->returnSuccess($products);
    }
    
    /*
     * 获取商品的详细信息
     */
    public function detail(Request $request)
    {
        $id = $request->get('id');
		$longitude = $request->get('longitude');
		$latitude  = $request->get('latitude');
		if ($request->user()) {
			$user_id = $request->user()->id;
		} else {
			$user_id = -1;
		}

        $product = Product::with('shop')->with('coupons')->where('id', '=', $id)->first();
        $pics = $product->pics;
        foreach ($pics as $key => $pic) {
            $new_pic = env('CUT_IMAGE_UTL') . $pic;
            $pics[$key] = $new_pic;
        }
		if($product->view_pic){
			$product->view_pic = env('CUT_IMAGE_UTL') .$product->view_pic;
		}
        $coupons = $product->coupons;
        foreach ($coupons as $coupon) {
            $coupon->is_fetched = 'N';
            $userCoupon = UserCoupon::where('user_id', '=', $user_id)
                        ->where('p_id', '=', $coupon->pivot->p_id)
                        ->where('c_id', '=', $coupon->pivot->c_id)
                        ->first();
            if ($userCoupon) {
                $coupon->is_fetched = 'Y';
            }
        }
        $product->pics = $pics;
		$product->distance = 0;//$this->getShopDistance($product->shop_id, $longitude, $latitude);
        return $this->returnSuccess($product);
    }
	
    
    /**
     * 获取优惠券
     * @param {Object} Request $request
     */
    public function fetchCoupon(Request $request)
    {
		$user_id = $request->user()->id;
        $p_id    = $request->get('p_id');
        $c_id    = $request->get('c_id');
        $userCoupon = UserCoupon::where('user_id', '=', $user_id)
                        ->where('p_id', '=', $p_id)
                        ->where('c_id', '=', $c_id)
                        ->first();
        if (empty($userCoupon)) {
			$pc = ProductCoupon::where("p_id", '=', $p_id)->where("c_id", "=", $c_id)->first();
			if (empty($pc)) {
				return $this->returnSuccess('Y');
			}
			$pcc = ProductCouponCode::where('pc_id', "=", $pc->id)->where('status', '=', 'N')->first();
			if (empty($pcc)) {
				return $this->returnFail('领取失败，您来晚了，优惠券已经领完');
			}
			$pcc->user_id = $user_id;
			$pcc->save();
            $userCoupon = new UserCoupon();
            $userCoupon->user_id = $user_id;
            $userCoupon->p_id    = $p_id;
            $userCoupon->c_id    = $c_id;
            $userCoupon->save();
        } else {
            return $this->returnSuccess('Y');
        }
        return $this->returnSuccess('Y');
    }
    
    public function redisTest()
    {
		$longitude = '11.1133';
		$latitude  = '22.2244';
		$database  = 'laravel_database_cut_location';
		$queryNum  = 5;
        $values = Redis::command('georadius', [$database, $longitude, $latitude, '100', 'km', 'WITHDIST', 'WITHCOORD', 'ASC', 'COUNT', $queryNum]);
		$shop_ids = [];
		foreach ($values as $item) {
			\array_push($shop_ids, \explode('_', $item[0])[1]);
		}
		$products = Product::whereIn('shop_id', $shop_ids)->get();
		foreach ($products as $product) {
			foreach ($values as $item) {
				if ($product->shop_id == explode('_', $item[0])[1]) {
					$product->distance = $item[1];
				}
			}
		}
		return $products;
    }
	/**
	 * 获取我的优惠券数量
	 */
	public function myCouponNumber(Request $request) {
		$user_id = $request->user()->id;
		$count   = ProductCouponCode::where("user_id", '=', $user_id)->count();
		return $this->returnSuccess($count);
	}
	
	/**
	 * 获取我的优惠券
	 */
	public function getMyCoupons(Request $request) {
		$user_id     = $request->user()->id;
		$pageSize    = $request->get('size');
		if (empty($pageSize)) {
			$pageSize = 5;
		}
		$page        = $request->get('page');
		$begin       = ( $page - 1 ) * $pageSize;
		$status      = $request->get('status');
		$query       = ProductCouponCode::where("user_id", '=', $user_id);
		if ($status != 'A') {
			$query->where("status", '=', $status);
		}
		$total       = $query->count();
		$productCouponCodes = $query->offset($begin)->limit($pageSize)->get();
		foreach ($productCouponCodes as &$productCouponCode) {
			
			$productCoupon      = ProductCoupon::where("id", '=', $productCouponCode->pc_id)->first();
			if($productCoupon){
				$product            = Product::where("id", "=", $productCoupon->p_id)->first();
				$coupon             = Coupon::where('id', "=", $productCoupon->c_id)->first();
				$productCouponCode->money   = $coupon->reduce_price;
				$productCouponCode->end_date= $product->end_date;
				$productCouponCode->title   = $product->title;
				$productCouponCode->price   = $coupon->price;
			}
		}
		return $this->returnSuccess(array('data'=>$productCouponCodes, 'total' => $total));
	}
	
	public function useMyCoupon(Request $request) {
		$id = $request->get('id');
		if (empty($id)) {
			return $this->returnFail('id can not be null');
		}
		$productCouponCode = ProductCouponCode::where('id', '=', $id)->first();
		if (empty($productCouponCode)) {
			return $this->returnFail('code can not been found');
		}
		$productCouponCode->status='U';
		$productCouponCode->save();
		return $this->returnSuccess(array('ok'));
	}
	
}
